﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Media;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Mengsk.ProxyDelivery.Converters
{
    public class WebUrlImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null)
            {
                return null;
            }

            if (value is string == false)
            {
                return value;
            }

            string s = value.ToString();
            if (string.IsNullOrWhiteSpace(s))
            {
                return null;
            }
            if (s.StartsWith("http:", StringComparison.OrdinalIgnoreCase))
            {
                BitmapImage image = new BitmapImage(new Uri(s, UriKind.Absolute));
                return image;
            }
            else if ("abcdefghijk".Any(c => char.ToLower(s[0]) == c) && s[1] == ':')
            {
                BitmapImage image = new BitmapImage(new Uri(s, UriKind.Absolute));
                return image;
            }
            else
            {
                if (s.Contains("/images"))
                {
                    s = s.Substring("/images".Length);
                }
                BitmapImage image = new BitmapImage(new Uri(Service.ServiceContainer.ServerAddress + "/webservice/image/" + s, UriKind.Absolute));
                return image;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
